import axios from 'axios';

// 超时时间
axios.defaults.timeout = 5000
// http请求拦截器
axios.interceptors.request.use(config => {
  // console.log('loading open')
  return config
}, error => {
  // console.log('加载超时')
  return Promise.reject(error)
})
// http响应拦截器
axios.interceptors.response.use(data => {
  // console.log('loading close')
  return data
}, error => {
  // console.log('加载失败')
  return Promise.reject(error)
})

var axiosConfig = {
  serviceConfig: {
    url: '/',
    method: 'post',
    baseURL: process.env.API_ROOT,
    headers: {'X-Requested-With': 'XMLHttpRequest'},
    data: {},
    timeout: 10000,
    responseType: 'json',
    withCredentials: true
  },
  fileConfig: {
    url: '/',
    method: 'post',
    baseURL: process.env.API_ROOT,
    headers: {'Content-Type': 'multipart/form-data'},
    timeout: 10000,
    responseType: 'json',
    withCredentials: true
  }
}

export default {
  post: function (url, params, callback, errCallback) {
    axios.post(url, params, axiosConfig.serviceConfig).then((res) => {
    	if (res.data.status === 0) {
    		callback(res.data)
    	} else {
    		typeof errCallback === 'function' ? errCallback(res) : alert(res.data.msg)
    	}
    }).catch((err) => {
    	alert(err)
    })
  },
  get: function (url, callback, errCallback) {
    axios.get(url, axiosConfig.serviceConfig).then((res) => {
    	if (res.data.status === 0) {
    		callback(res.data)
    	} else {
    		typeof errCallback === 'function' ? errCallback(res) : alert(res.data.msg)
    	}
    }).catch((err) => {
    	alert(err)
    })
  },
  postFile: function (url, params, callback, errCallback) {
    axios.post(url, params, axiosConfig.fileConfig).then((res) => {
    	if (res.data.status === 0) {
    		callback(res.data)
    	} else {
    		typeof errCallback === 'function' ? errCallback(res.data) : alert(res.data.msg)
    	}
    }).catch((err) => {
    	alert(err)
    })
  }
}